<template>
	<a-modal v-model="showModal" @ok="confirmOk" @cancel="cancel" :title="titles" width="70%">
		<a-spin :spinning="loading">
			<a-form :form="form">
				<a-row :gutter="[24, 0]">
					<a-col :span="12">
						<a-form-item class="mb-15" label="商品名称" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input placeholder="请输入" v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }]
                  }
                ]" maxLength="30"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="商品图片" :label-col="labelCol" :wrapper-col="wrapperCol">
							<PreviewImage :showUpload="isShow" class="mt-12" :is-preview="false" :scene="8"
								:show-upload="formgetFileLength(`picUrl`) < 1"
								@uploadSuccess="formuploadSuccess($event, `picUrl`)" v-decorator="[
                  `picUrl`,
                  {
                    rules: [{ required: true, message: '请上传图片', type: 'array' }],
                    initialValue: []
                  }
                ]" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="[24, 0]">
					<a-col :span="12">
						<div style="margin-left: 133px;" class="flex">
							<div style="width: 240px;">
								<a-form-item class="mb-15" label="商品分类" :label-col="labelCol" :wrapper-col="wrapperCol">

									<a-select class="flex-1" @change="changeSelect" placeholder="请选择"
										v-decorator="['firstCategoryId', { rules: [{ required: true, message: '请选择' }] }]">
										<a-select-option :value="1">你好 </a-select-option>
										<a-select-option :value="2">不好 </a-select-option>
									</a-select>

								</a-form-item>
							</div>
							<div style="width: 240px;">
								<a-form-item class="mb-15">

									<a-select class="flex-1" @change="changeSelect" placeholder="请选择"
										v-decorator="['secondCategoryId', { rules: [{ required: true, message: '请选择' }] }]">
										<a-select-option :value="1">你好 </a-select-option>
										<a-select-option :value="2">不好 </a-select-option>
									</a-select>

								</a-form-item>
							</div>
						</div>
					</a-col>
				</a-row>
				<a-row :gutter="[24, 0]">
					<a-col :span="12">
						<a-form-item class="mb-15" label="库存单位" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-input placeholder="请输入" v-decorator="[
                  'unit',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }]
                  }
                ]" maxLength="30"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="运费" :label-col="labelCol" :wrapper-col="wrapperCol">
							<div style="display:flex">
								<a-input placeholder="请输入" v-decorator="[
                    'freight',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true }]
                    }
                  ]" maxLength="30"></a-input>元
							</div>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item class="mb-15" label="商品简介" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
							<a-textarea placeholder="请输入" v-decorator="[
                    'introduction',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true }]
                    }
                  ]" maxLength="300"></a-textarea>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="[24, 0]">
					<a-col :span="12">
						<a-form-item class="mb-15" label="商品宣传视频" :label-col="labelCol" :wrapper-col="wrapperCol">
							<PreviewImage :showUpload="isShow" class="mt-12" :is-preview="false" :scene="8"
								:show-upload="formgetFileLength(`videoUrl`) < 1"
								@uploadSuccess="formuploadSuccess($event, `videoUrl`)" v-decorator="[
                  `videoUrl`,
                  {
                    rules: [{ required: true, message: '请上传', type: 'array' }],
                    initialValue: []
                  }
                ]" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item class="mb-15" label="状态" :label-col="labelCol" :wrapper-col="wrapperCol">
							<a-switch checked-children="已上架" un-checked-children="未上架"
								v-decorator="['status', { valuePropName: 'checked' }]" />
						</a-form-item>
					</a-col>
				</a-row>
				<div>商品规格：</div>
				<a-row :gutter="24">
					<a-col :span="24">
						<a-table class="mt-16 order-table" :columns="columns" :data-source="dataSource"
							:pagination="false">
							<template #name="name, data">
								<a-input v-model="data.name" placeholder="请输入" />
							</template>
							<template #picUrl="picUrl, data">
								<div class="flex items-center justify-center">
									<PreviewImage :showUpload="data.picUrl.length<1?true:false" :is-preview="false"
										:scene="1" @uploadSuccess="getormuploadSuccess($event, data)"
										v-model="data.picUrl" />
								</div>

							</template>
							<template #stock="stock, data">
								<a-input v-model="data.stock" placeholder="请输入" />
							</template>
							<template #price="price, data">
								<a-input v-model="data.price" placeholder="请输入" />
							</template>
							<template #action="action, data">
								<div class="flex items-center justify-center">
									<a-button @click="onDelete(data.key)" class="ml-10 mr-10" type="danger">
										删除
									</a-button>
									<a-button v-if="dataSource.length && data === dataSource[dataSource.length - 1]"
										@click="handleAdd" class="mr-10" type="primary">
										添加
									</a-button>
								</div>
							</template>
						</a-table>
					</a-col>
				</a-row>
				<div class="mt-20 mb-20">产品详情：</div>
				<a-row :gutter="24">
					<a-col :span="24">
						<quill-editor class="editor" v-model="content" ref="myQuillEditor" :options="editorOption"
							@blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)"
							@ready="onEditorReady($event)">
						</quill-editor>
					</a-col>
				</a-row>
			</a-form>
		</a-spin>
	</a-modal>
</template>
<script>
	import {
		quillEditor
	} from 'vue-quill-editor'
	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.snow.css'
	import 'quill/dist/quill.bubble.css'
	import {
		get
	} from 'lodash'
	import {
		deductionDetail,
		getBanner
	} from '@/api/newPet'
	export default {
		data() {
			return {
				loading: false,
				isShow: true,
				labelCol: {
					span: 8
				},
				content: '<p>Hello World!</p>',

				editorOption: {
					placeholder: '请输入',
					theme: 'snow',
					modules: {
						toolbar: {
							container: [
								['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
								['blockquote', 'code-block'], // 引用  代码块
								[{
									header: 1
								}, {
									header: 2
								}], // 1、2 级标题
								[{
									list: 'ordered'
								}, {
									list: 'bullet'
								}], // 有序、无序列表
								[{
									script: 'sub'
								}, {
									script: 'super'
								}], // 上标/下标
								[{
									indent: '-1'
								}, {
									indent: '+1'
								}], // 缩进
								// [{ direction: 'rtl' }], // 文本方向
								[{
									size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36']
								}], // 字体大小
								[{
									header: [1, 2, 3, 4, 5, 6]
								}], // 标题
								[{
									color: []
								}, {
									background: []
								}], // 字体颜色、字体背景颜色
								// [{ font: ['songti'] }], // 字体种类
								[{
									align: []
								}], // 对齐方式
								['clean'], // 清除文本格式
								['image'] // 链接、图片，需要视频的可以加上video
							]
						}
					}
				},
				count: 1,
				dataSource: [{
					name: '规格0',
					picUrl: [],
					stock: 1,
					price: 1,
					key: 0
				}],
				columns: [{
						title: '规格名称',
						dataIndex: 'name',
						align: 'center',
						width: 140,
						scopedSlots: {
							customRender: 'name'
						}
					},
					{
						title: '规格图片',
						dataIndex: 'picUrl',
						width: 120,
						align: 'center',
						scopedSlots: {
							customRender: 'picUrl'
						}
					},
					{
						title: '规格库存',
						dataIndex: 'stock',
						align: 'center',
						width: 70,
						scopedSlots: {
							customRender: 'stock'
						}
					},
					{
						title: '规格价格（元）',
						dataIndex: 'price',
						align: 'center',
						width: 70,
						scopedSlots: {
							customRender: 'price'
						}
					},
					{
						title: '操作',

						dataIndex: 'action',
						width: 160,
						scopedSlots: {
							customRender: 'action'
						},
						align: 'center'
					}
				],

				wrapperCol: {
					span: 16
				},
				details: {},
				showModal: false,
				titles: '新增',
				info: {},
				form: this.$form.createForm(this)
			}
		},
		computed: {},
		watch: {},
		async created() {},
		components: {
			quillEditor
		},
		methods: {
			handleAdd() {
				const {
					dataSource,
					count
				} = this;
				const newData = {
					name: `规格 ${count}`,
					key: count,
					picUrl: [],
					stock: '1',
					price: '1'

				};
				this.count = count + 1;
				this.dataSource = [...dataSource, newData]
				console.log(this.dataSource, 'xxx')
			},
			onDelete(key) {
				const dataSource = [...this.dataSource];
				this.dataSource = dataSource.filter(item => item.key !== key);
			},
			onEditorBlur(quill) {
				console.log('editor blur!', quill)
			},
			// 获得焦点事件
			onEditorFocus(quill) {
				console.log('editor focus!', quill)
			},
			// 准备富文本编辑器
			onEditorReady(quill) {
				console.log('editor ready!', quill)
			},
			// 内容改变事件，只需要这一个方法就够了
			onEditorChange({
				quill,
				html,
				text
			}) {
				console.log('editor change!', quill, html, text)
				this.content = html
			},
			getFormgetFileLength(type) {
				return get(type, 'length') || 0
			},
			formgetFileLength(type) {
				//获取图片
				return get(this.form.getFieldValue(type), 'length') || 0
			},
			getormuploadSuccess(data, item) {
				item.picUrl = [...item.picUrl, data.path];
			},
			formuploadSuccess(data, type) {
				this.form.setFieldsValue({
					[type]: [...this.form.getFieldValue(type), data.path]
				})
			},
			changeSelect(e) {
				console.log(e)
			},
			onChange(e) {
				console.log(e.target.value)
			},
			cancel() {
				this.form.resetFields()
				this.showModal = false
			},
			confirmOk() {
				this.form.validateFields((err, values) => {
					if (!err) {
						// this.loading = true
						const {
							info
						} = this
						let skus = this.dataSource
						skus.forEach(item => {
							if (Array.isArray(item.picUrl)) {
								item.picUrl = item.picUrl.join(', '); // 将数组转换为以逗号分隔的字符串
							}
						});
						let data = {
							id: info && info.id ? info.id : undefined,
							...this.$utils.trimValue(values),
							status: typeof values.status === 'undefined' ? 0 : values.status ? 0 : 1,
							skus: skus,
							description: this.content
						}
						console.log('data', data)
						return
						const fun = info && info.id ? deductionDetail : deductionDetail
						fun(data)
							.then(() => {
								this.$message.success(info && info.id ? '修改成功！' : '新增成功！')
								this.$emit('upload')
								this.cancel()
							})
							.finally(() => {
								this.loading = false
							})
					}
				})
			},
			getData() {
				this.loading = true
				deductionDetail({
						id: 1
					})
					.then(data => {
						this.details = data
					})
					.finally(() => (this.loading = false))
			},
			open(data) {
				this.info = data
				console.log(data, '111111')
				if (data.id) {
					this.titles = '修改'
				} else {
					this.titles = '新增'
				}
				this.showModal = true
				// images:['https://img2.baidu.com/it/u=1906732828,3160455141&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666']
				this.$nextTick(() => {
					this.form.setFieldsValue({
						isEnabled: true
					})
				})
				// this.$emit('upload')
				// this.$nextTick(() => {
				//     this.form.setFieldsValue({
				// 					...res
				// 				})

				// 			})
			}
		}
	}
</script>
<style lang="less" scoped>
	/deep/ .ant-form-item-label {
		// width: 100px;
	}
</style>